import { Ref } from 'vue';

export interface TreeNode {
  id: string | number;
  checked?: boolean;
  children?: TreeNode[];
}

export const useTreeCascadeCheck = (
  permissionTree: Ref<TreeNode[]>,
  treeRef: Ref<any>
) => {
  // 递归子节点变为false
  const updateChildrenChecked = (children: TreeNode[], checked: boolean) => {
    for (let i = 0; i < children.length; i++) {
      const child = children[i];
      child.checked = checked;
      treeRef.value?.setChecked(child.id, checked);
      if (child.children && child.children.length > 0) {
        updateChildrenChecked(child.children, checked);
      }
    }
  };

  // 从根节点开始遍历找到父节点
  const findParentNode = (
    nodes: TreeNode[],
    targetId: string | number
  ): TreeNode | null => {
    for (const node of nodes) {
      if (node.children) {
        for (const child of node.children) {
          if (child.id === targetId) {
            return node;
          }
        }
        const found = findParentNode(node.children, targetId);
        if (found) return found;
      }
    }
    return null;
  };

  // 递归更新父节点的checked状态为true
  const updateParentChecked = (node: TreeNode) => {
    const parentNode = findParentNode(permissionTree.value, node.id);
    if (parentNode) {
      parentNode.checked = true;
      updateParentChecked(parentNode);
    }
  };

  // 处理节点选中状态变化
  const handleTreeChangePermission = async (
    data: TreeNode,
    checked: boolean,
    childChecked: boolean
  ) => {
    data.checked = checked;

    // 如果当前节点改为false，将所有子节点改为false
    if (!checked && data.children && data.children.length > 0) {
      updateChildrenChecked(data.children, false);
    }

    // 如果当前节点改为true，将所有父节点改为true
    if (checked) {
      updateParentChecked(data);
    }
  };

  return {
    updateChildrenChecked,
    findParentNode,
    updateParentChecked,
    handleTreeChangePermission,
  };
};
